#!/usr/bin/env python3
"""
批量生成Mermaid图表的PNG图片
Generate PNG images from all Mermaid files in diagrams directory
"""
import os
import subprocess
import sys
from pathlib import Path

def generate_all_diagrams():
    """Generate all PNG images from Mermaid files"""
    base_dir = Path("diagrams")
    generated_count = 0
    failed_count = 0
    
    print("🎨 开始生成PNG图片...")
    print(f"扫描目录: {base_dir.absolute()}")
    
    if not base_dir.exists():
        print(f"❌ 错误: 目录 {base_dir} 不存在")
        return False
    
    # 查找所有.mmd文件
    mmd_files = list(base_dir.glob("**/*.mmd"))
    
    if not mmd_files:
        print("❌ 没有找到任何.mmd文件")
        return False
    
    print(f"找到 {len(mmd_files)} 个Mermaid文件:")
    for mmd_file in mmd_files:
        print(f"  - {mmd_file}")
    
    # 生成每个PNG图片
    for mmd_file in mmd_files:
        png_file = mmd_file.with_suffix('.png')
        
        print(f"\n📊 正在处理: {mmd_file.name}")
        
        try:
            # 使用mmdc命令生成PNG
            # 设置较高的分辨率和质量参数
            cmd = [
                'mmdc',
                '-i', str(mmd_file),
                '-o', str(png_file),
                '-w', '1200',     # 宽度1200px
                '-H', '800',      # 高度800px
                '-s', '2',        # 缩放因子2x (提高清晰度)
                '-t', 'neutral',  # 中性主题
                '-b', 'white'     # 白色背景
            ]
            
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
            
            if result.returncode == 0:
                # 检查生成的文件大小
                if png_file.exists() and png_file.stat().st_size > 1000:  # 至少1KB
                    file_size = png_file.stat().st_size / 1024  # KB
                    print(f"✅ 成功生成: {png_file.name} ({file_size:.1f}KB)")
                    generated_count += 1
                else:
                    print(f"⚠️  警告: 生成的文件太小或不存在: {png_file.name}")
                    failed_count += 1
            else:
                print(f"❌ 生成失败: {mmd_file.name}")
                print(f"   错误信息: {result.stderr}")
                failed_count += 1
                
        except subprocess.TimeoutExpired:
            print(f"❌ 超时: {mmd_file.name} (30秒)")
            failed_count += 1
        except FileNotFoundError:
            print("❌ 错误: 未找到mmdc命令，请确保已安装 @mermaid-js/mermaid-cli")
            print("   安装命令: npm install -g @mermaid-js/mermaid-cli")
            return False
        except Exception as e:
            print(f"❌ 未知错误处理 {mmd_file.name}: {e}")
            failed_count += 1
    
    print(f"\n📊 生成统计:")
    print(f"   ✅ 成功: {generated_count} 个")
    print(f"   ❌ 失败: {failed_count} 个")
    print(f"   📁 总计: {len(mmd_files)} 个")
    
    return generated_count > 0

def verify_generated_images():
    """验证生成的PNG文件"""
    base_dir = Path("diagrams")
    png_files = list(base_dir.glob("**/*.png"))
    
    print(f"\n🔍 验证生成的PNG文件...")
    
    if not png_files:
        print("❌ 没有找到任何PNG文件")
        return False
    
    valid_count = 0
    for png_file in png_files:
        file_size = png_file.stat().st_size
        if file_size > 5000:  # 至少5KB
            print(f"✅ {png_file.name}: {file_size/1024:.1f}KB")
            valid_count += 1
        else:
            print(f"⚠️  {png_file.name}: {file_size/1024:.1f}KB (文件太小)")
    
    print(f"\n验证结果: {valid_count}/{len(png_files)} 个文件有效")
    return valid_count == len(png_files)

def main():
    """主函数"""
    print("=" * 60)
    print("🎨 Mermaid图表PNG生成器")
    print("=" * 60)
    
    # 确保在正确的目录中
    script_dir = Path(__file__).parent
    os.chdir(script_dir)
    
    print(f"当前工作目录: {os.getcwd()}")
    
    # 生成图片
    success = generate_all_diagrams()
    
    if success:
        # 验证生成的图片
        verify_generated_images()
        print("\n🎉 图片生成完成!")
    else:
        print("\n❌ 图片生成失败!")
        sys.exit(1)

if __name__ == "__main__":
    main()